package com.example.analysis.utils;

import java.util.ArrayList;
import java.util.List;

// 方差齐性检验
public class LeveneTest {
    /**
     * Levene 检验（支持均值或中位数）
     *
     * @param groups    每组数据
     * @param useMedian true=用中位数，false=用均值
     * @return p值 >= 0.05，则方差齐
     */
    public static double leveneTest(List<double[]> groups, boolean useMedian) {
        // 1. 准备ANOVA输入
        List<double[]> deviationGroups = new ArrayList<>();
        for (double[] group :
                groups) {
            // 1. 计算每组的绝对偏差
            double[] dev = calculateAbsoluteDeviations(group, useMedian);
            deviationGroups.add(dev);
        }
        // 2.ANOVA分析
        System.out.println("deviationGroups.size() = " + deviationGroups.size());
        return OneWayAnova.calculateANOVAPValue(deviationGroups, null);
    }

    // 计算绝对偏差（基于中位数或均值）
    private static double[] calculateAbsoluteDeviations(double[] data, boolean useMedian) {
        double center = useMedian ? ComCalcUtils.calcMedian(data) : ComCalcUtils.calcMean(data);
        double[] deviations = new double[data.length];
        for (int i = 0; i < data.length; i++) {
            deviations[i] = Math.abs(data[i] - center);
        }
        return deviations;
    }
}
